// 注册灌溉管理页面处理程序
pageManager.registerPage('irrigation', {
    // 保存页面状态
    chartInstance: null,
    currentMode: 'auto',
    isIrrigating: false,
    waterAmount: 5.0,

    init() {
        this.initChart();
        this.initControls();
        this.initScheduleTable();
        this.startDataUpdate();
        this.initAlerts();
    },

    cleanup() {
        if (this.chartInstance) {
            this.chartInstance.dispose();
        }
        // 清理定时器等资源
        if (this.updateTimer) {
            clearInterval(this.updateTimer);
        }
    },

    // 初始化图表
    initChart() {
        const chartDom = document.getElementById('irrigationChart');
        this.chartInstance = echarts.init(chartDom);
        
        // 监听数据类型切换
        document.getElementById('dataType').addEventListener('change', (e) => {
            this.updateChart(e.target.value);
        });

        // 默认显示土壤墒情数据
        this.updateChart('moisture');
    },

    // 更新图表数据和分析指标
    updateChart(dataType) {
        // 获取时间范围
        const timeRange = document.getElementById('timeRange').value;
        const data = this.generateData(dataType, timeRange);
        
        // 更新图表
        let option = {
            title: {
                text: this.getChartTitle(dataType),
                left: 'center'
            },
            tooltip: {
                trigger: 'axis',
                formatter: (params) => {
                    return this.formatTooltip(params, dataType);
                }
            },
            legend: {
                data: this.getLegendData(dataType),
                bottom: 0
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '60px',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: data.time,
                axisLabel: {
                    rotate: 45
                }
            },
            yAxis: this.getYAxisConfig(dataType),
            series: data.series
        };
        
        this.chartInstance.setOption(option, true);
        
        // 更新分析指标
        this.updateAnalysisMetrics(data.series[0].data);
    },

    // 获取图表标题
    getChartTitle(dataType) {
        const titles = {
            moisture: '土壤墒情变化趋势',
            water: '灌溉用水量分析',
            efficiency: '灌溉效率评估'
        };
        return titles[dataType] || '';
    },

    // 获取Y轴配置
    getYAxisConfig(dataType) {
        const configs = {
            moisture: {
                type: 'value',
                name: '土壤含水量(%)',
                min: 0,
                max: 100,
                splitLine: {
                    show: true,
                    lineStyle: {
                        type: 'dashed'
                    }
                }
            },
            water: {
                type: 'value',
                name: '用水量(m³/亩)',
                min: 0,
                splitLine: {
                    show: true
                }
            },
            efficiency: [{
                type: 'value',
                name: '利用率(%)',
                min: 0,
                max: 100,
                position: 'left'
            }, {
                type: 'value',
                name: '节水量(m³)',
                min: 0,
                position: 'right'
            }]
        };
        return configs[dataType];
    },

    // 获取图例数据
    getLegendData(dataType) {
        const legendData = {
            moisture: ['实际墒情', '适宜范围'],
            water: ['实际用水', '计划用水'],
            efficiency: ['灌溉利用率', '累计节水量']
        };
        return legendData[dataType] || [];
    },

    // 格式化提示框
    formatTooltip(params, dataType) {
        const time = params[0].name;
        let result = `${time}<br/>`;
        
        switch(dataType) {
            case 'moisture':
                result += `${params[0].seriesName}: ${params[0].value}%`;
                break;
            case 'water':
                result += `${params[0].seriesName}: ${params[0].value} m³/亩<br/>`;
                result += `${params[1].seriesName}: ${params[1].value} m³/亩`;
                break;
            case 'efficiency':
                result += `${params[0].seriesName}: ${params[0].value}%<br/>`;
                result += `${params[1].seriesName}: ${params[1].value} m³`;
                break;
        }
        
        return result;
    },

    // 生成不同时间范围的数据
    generateData(dataType, timeRange) {
        const timeData = this.generateTimePoints(timeRange);
        let seriesData = [];
        
        switch(dataType) {
            case 'moisture':
                seriesData = this.generateMoistureData(timeRange);
                break;
            case 'water':
                seriesData = this.generateWaterUsageData(timeRange);
                break;
            case 'efficiency':
                seriesData = this.generateEfficiencyData(timeRange);
                break;
        }
        
        return {
            time: timeData,
            series: seriesData
        };
    },

    // 生成时间点
    generateTimePoints(timeRange) {
        const points = [];
        const now = new Date();
        let count;
        
        switch(timeRange) {
            case 'day':
                count = 24;
                for (let i = 0; i < count; i++) {
                    points.push(new Date(now - (23-i) * 3600000).toLocaleTimeString('zh-CN', {
                        hour: '2-digit',
                        minute: '2-digit'
                    }));
                }
                break;
            case 'week':
                count = 7;
                for (let i = 0; i < count; i++) {
                    points.push(new Date(now - (6-i) * 86400000).toLocaleDateString('zh-CN', {
                        month: 'numeric',
                        day: 'numeric'
                    }));
                }
                break;
            case 'month':
                count = 30;
                for (let i = 0; i < count; i++) {
                    points.push(new Date(now - (29-i) * 86400000).toLocaleDateString('zh-CN', {
                        month: 'numeric',
                        day: 'numeric'
                    }));
                }
                break;
        }
        return points;
    },

    // 生成墒情数据
    generateMoistureData(timeRange) {
        const count = timeRange === 'day' ? 24 : (timeRange === 'week' ? 7 : 30);
        const data = [];
        let value = 45;
        
        for (let i = 0; i < count; i++) {
            // 模拟日变化规律
            const timeEffect = timeRange === 'day' ? 
                Math.sin(i / 24 * Math.PI * 2) * 5 : // 日内波动
                Math.sin(i / count * Math.PI) * 3;   // 长期趋势
            
            // 添加随机波动
            value += timeEffect + (Math.random() - 0.5) * 3;
            value = Math.min(Math.max(value, 30), 70);
            
            data.push(parseFloat(value.toFixed(1)));
        }
        
        return [{
            name: '土壤墒情',
            type: 'line',
            smooth: true,
            data: data,
            areaStyle: {
                opacity: 0.3
            }
        }];
    },

    // 生成用水量数据
    generateWaterUsageData(timeRange) {
        const count = timeRange === 'day' ? 24 : (timeRange === 'week' ? 7 : 30);
        const actualData = [];
        const plannedData = [];
        
        for (let i = 0; i < count; i++) {
            // 基础用水量
            const baseAmount = timeRange === 'day' ? 
                4 + Math.sin(i / 24 * Math.PI * 2) * 2 : // 日内变化
                5 + Math.sin(i / count * Math.PI) * 1;   // 长期趋势
            
            // 计划用水量
            plannedData.push(parseFloat(baseAmount.toFixed(1)));
            
            // 实际用水量（添加随机偏差）
            const actualAmount = baseAmount * (0.9 + Math.random() * 0.2);
            actualData.push(parseFloat(actualAmount.toFixed(1)));
        }
        
        return [{
            name: '实际用水',
            type: 'bar',
            data: actualData,
            itemStyle: {
                color: '#4CAF50'
            }
        }, {
            name: '计划用水',
            type: 'line',
            smooth: true,
            data: plannedData,
            lineStyle: {
                type: 'dashed'
            }
        }];
    },

    // 生成效率数据
    generateEfficiencyData(timeRange) {
        const efficiency = [];
        const savings = [];
        let accumSavings = 0;
        
        for (let i = 0; i < 24; i++) {
            // 模拟灌溉效率（70%-95%之间波动）
            const eff = 70 + Math.random() * 25;
            efficiency.push(eff.toFixed(1));
            
            // 累计节水量
            const saving = Math.random() * 0.5;
            accumSavings += saving;
            savings.push(accumSavings.toFixed(1));
        }
        
        return [{
            name: '灌溉利用率',
            type: 'line',
            smooth: true,
            data: efficiency,
            yAxisIndex: 0,
            itemStyle: {
                color: '#2196F3'
            }
        }, {
            name: '累计节水量',
            type: 'bar',
            data: savings,
            yAxisIndex: 1,
            itemStyle: {
                color: '#81C784'
            }
        }];
    },

    // 更新分析指标
    updateAnalysisMetrics(data) {
        // 计算统计指标
        const avg = data.reduce((a, b) => a + b) / data.length;
        const max = Math.max(...data);
        const min = Math.min(...data);
        
        // 计算标准差
        const variance = data.reduce((a, b) => a + Math.pow(b - avg, 2), 0) / data.length;
        const std = Math.sqrt(variance);
        
        // 更新显示
        document.getElementById('avgValue').textContent = avg.toFixed(1);
        document.getElementById('maxValue').textContent = max.toFixed(1);
        document.getElementById('minValue').textContent = min.toFixed(1);
        document.getElementById('stdValue').textContent = std.toFixed(2);
    },

    // 更新统计信息
    updateStatistics() {
        const stats = {
            monthlyCount: Math.floor(10 + Math.random() * 5),
            totalWater: parseFloat((120 + Math.random() * 60).toFixed(1)),
            efficiency: parseFloat((80 + Math.random() * 15).toFixed(1)),
            savingRate: parseFloat((10 + Math.random() * 10).toFixed(1))
        };

        // 更新统计面板
        const statItems = document.querySelectorAll('.statistics-list .value');
        statItems[0].textContent = `${stats.monthlyCount}次`;
        statItems[1].textContent = `${stats.totalWater} m³`;
        statItems[2].textContent = `${stats.efficiency}%`;
        statItems[3].textContent = `${stats.savingRate}%`;

        return stats;
    },

    // 更新状态卡片
    updateStatusCards() {
        const todayWater = parseFloat((100 + Math.random() * 50).toFixed(1));
        const duration = parseFloat((2 + Math.random() * 1).toFixed(1));
        const uniformity = parseFloat((85 + Math.random() * 10).toFixed(1));
        
        const cards = document.querySelectorAll('.status-card p');
        cards[0].textContent = `${todayWater} m³`;
        cards[1].textContent = `${duration} 小时`;
        cards[2].textContent = `${uniformity}%`;
        
        // 更新需水预警状态
        const warningStatus = this.calculateWarningStatus();
        cards[3].textContent = warningStatus;
        cards[3].className = `status ${warningStatus.toLowerCase()}`;
    },

    // 计算需水预警状态
    calculateWarningStatus() {
        const moisture = parseFloat(document.getElementById('currentMoisture').textContent);
        if (moisture < 35) return '需要灌溉';
        if (moisture > 65) return '水分过多';
        return '正常';
    },

    // 初始化控制面板
    initControls() {
        // 灌溉模式选择
        const modeSelect = document.getElementById('irrigationMode');
        modeSelect.addEventListener('change', (e) => {
            this.currentMode = e.target.value;
            this.updateControlState();
        });

        // 水量控制
        const decreaseBtn = document.querySelector('.water-control .decrease');
        const increaseBtn = document.querySelector('.water-control .increase');
        const waterAmount = document.getElementById('waterAmount');

        decreaseBtn.addEventListener('click', () => {
            if (this.waterAmount > 0.5) {
                this.waterAmount -= 0.5;
                waterAmount.textContent = this.waterAmount.toFixed(1);
            }
        });

        increaseBtn.addEventListener('click', () => {
            if (this.waterAmount < 10.0) {
                this.waterAmount += 0.5;
                waterAmount.textContent = this.waterAmount.toFixed(1);
            }
        });

        // 灌溉控制按钮
        const startBtn = document.getElementById('startIrrigation');
        const stopBtn = document.getElementById('stopIrrigation');

        startBtn.addEventListener('click', () => {
            this.startIrrigation();
        });

        stopBtn.addEventListener('click', () => {
            this.stopIrrigation();
        });
    },

    // 更新控制状态
    updateControlState() {
        const startBtn = document.getElementById('startIrrigation');
        const stopBtn = document.getElementById('stopIrrigation');
        const waterControl = document.querySelector('.water-control');

        if (this.currentMode === 'auto') {
            startBtn.disabled = true;
            stopBtn.disabled = true;
            waterControl.style.opacity = '0.5';
            waterControl.style.pointerEvents = 'none';
        } else {
            startBtn.disabled = this.isIrrigating;
            stopBtn.disabled = !this.isIrrigating;
            waterControl.style.opacity = '1';
            waterControl.style.pointerEvents = 'auto';
        }
    },

    // 开始灌溉
    startIrrigation() {
        this.isIrrigating = true;
        this.updateControlState();
        
        // 添加灌溉记录
        this.addScheduleRecord({
            time: new Date().toLocaleString(),
            amount: this.waterAmount,
            duration: '进行中',
            status: '灌溉中'
        });
    },

    // 停止灌溉
    stopIrrigation() {
        this.isIrrigating = false;
        this.updateControlState();
        
        // 更新最后一条记录状态
        const tbody = document.querySelector('#scheduleList');
        const lastRow = tbody.firstElementChild;
        if (lastRow) {
            lastRow.cells[2].textContent = '30分钟';
            lastRow.cells[3].textContent = '已完成';
        }
    },

    // 初始化计划表格
    initScheduleTable() {
        // 添加示例数据
        const sampleData = [
            {
                time: '2024-03-15 08:00',
                amount: 4.5,
                duration: '45分钟',
                status: '已完成'
            },
            {
                time: '2024-03-14 15:30',
                amount: 5.0,
                duration: '50分钟',
                status: '已完成'
            }
        ];

        sampleData.forEach(record => this.addScheduleRecord(record));

        // 添加新计划按钮事件
        document.getElementById('addSchedule').addEventListener('click', () => {
            this.showAddScheduleDialog();
        });
    },

    // 添加灌溉记录
    addScheduleRecord(record) {
        const tbody = document.querySelector('#scheduleList');
        const tr = document.createElement('tr');
        
        tr.innerHTML = `
            <td>${record.time}</td>
            <td>${record.amount} m³/亩</td>
            <td>${record.duration}</td>
            <td>${record.status}</td>
            <td>
                <button class="btn-control" onclick="pageManager.getPage('irrigation').deleteRecord(this)">
                    删除
                </button>
            </td>
        `;
        
        tbody.insertBefore(tr, tbody.firstChild);
    },

    // 删除记录
    deleteRecord(btn) {
        const tr = btn.closest('tr');
        tr.remove();
    },

    // 显示添加计划对话框
    showAddScheduleDialog() {
        // 这里可以实现添加计划的对话框
        alert('添加灌溉计划功能开发中...');
    },

    // 开始数据更新
    startDataUpdate() {
        // 初始更新
        this.updateStatistics();
        this.updateStatusCards();
        
        // 定时更新
        this.updateTimer = setInterval(() => {
            // 更新当前墒情
            const currentMoisture = document.getElementById('currentMoisture');
            const newValue = parseFloat(currentMoisture.textContent) + (Math.random() - 0.5) * 2;
            currentMoisture.textContent = `${Math.min(Math.max(newValue, 30), 70).toFixed(1)}%`;
            
            // 更新其他数据
            this.updateChart(document.getElementById('dataType').value);
            this.updateStatusCards();
            
            // 每小时更新一次统计信息
            if (new Date().getMinutes() === 0) {
                this.updateStatistics();
            }
        }, 60000); // 每分钟更新一次
    },

    // 初始化预警面板
    initAlerts() {
        // 监听预警筛选
        document.getElementById('alertFilter').addEventListener('change', (e) => {
            this.updateAlerts(e.target.value);
        });

        // 初始加载预警
        this.updateAlerts('all');
    },

    // 更新预警列表
    updateAlerts(filterType) {
        const alerts = this.generateAlerts(filterType);
        const alertList = document.getElementById('alertList');
        
        if (filterType === 'all') {
            // 按类型分组显示
            const categories = {
                moisture: { title: '墒情预警', alerts: [] },
                device: { title: '设备预警', alerts: [] },
                quality: { title: '水质预警', alerts: [] }
            };
            
            alerts.forEach(alert => {
                categories[alert.type].alerts.push(alert);
            });
            
            alertList.innerHTML = Object.entries(categories).map(([type, category]) => `
                ${category.alerts.length > 0 ? `
                    <div class="alert-category ${type}">${category.title}</div>
                    ${category.alerts.map(alert => this.renderAlertItem(alert)).join('')}
                ` : ''}
            `).join('');
        } else {
            alertList.innerHTML = alerts.map(alert => this.renderAlertItem(alert)).join('');
        }

        this.updateAlertSummary();
    },

    // 渲染单个预警项
    renderAlertItem(alert) {
        return `
            <div class="alert-item">
                <div class="alert-header">
                    <div class="alert-icon ${alert.level}">
                        ${this.getAlertIcon(alert.type)}
                    </div>
                    <span class="alert-title">
                        <span class="alert-badge ${alert.level}">
                            ${this.getLevelText(alert.level)}
                        </span>
                        ${alert.title}
                    </span>
                    <span class="alert-time">${alert.time}</span>
                </div>
                <div class="alert-message">${alert.message}</div>
                <div class="alert-actions">
                    <button class="btn-alert btn-handle" onclick="pageManager.getPage('irrigation').handleAlert(this)">
                        <span>✓</span> 处理
                    </button>
                    <button class="btn-alert btn-ignore" onclick="pageManager.getPage('irrigation').ignoreAlert(this)">
                        <span>×</span> 忽略
                    </button>
                </div>
            </div>
        `;
    },

    // 获取预警等级文本
    getLevelText(level) {
        const texts = {
            high: '紧急',
            medium: '警告',
            low: '提示'
        };
        return texts[level] || '普通';
    },

    // 生成更多样的预警数据
    generateAlerts(filterType) {
        // 生成各类预警数据
        const moistureAlerts = this.generateMoistureAlerts();
        const deviceAlerts = this.generateDeviceAlerts();
        const qualityAlerts = this.generateQualityAlerts();
        
        const alerts = [...moistureAlerts, ...deviceAlerts, ...qualityAlerts];
        
        if (filterType === 'all') return alerts;
        return alerts.filter(alert => alert.type === filterType);
    },

    // 生成墒情预警
    generateMoistureAlerts() {
        const currentMoisture = parseFloat(document.getElementById('currentMoisture').textContent);
        const alerts = [];

        // 严重缺水预警
        if (currentMoisture < 35) {
            alerts.push({
                type: 'moisture',
                level: 'high',
                title: '土壤墒情严重偏低',
                message: `当前土壤含水量${currentMoisture}%，低于作物安全水分阈值，建议立即进行灌溉。`,
                time: '刚刚'
            });
        }
        // 水分过量预警
        else if (currentMoisture > 65) {
            alerts.push({
                type: 'moisture',
                level: 'high',
                title: '土壤墒情过高',
                message: `当前土壤含水量${currentMoisture}%，超出适宜范围，存在渍害风险，建议暂停灌溉。`,
                time: '刚刚'
            });
        }
        // 墒情波动预警
        if (Math.random() > 0.7) {
            alerts.push({
                type: 'moisture',
                level: 'medium',
                title: '墒情波动异常',
                message: '最近24小时墒情波动幅度超过15%，建议检查灌溉系统设置和土壤渗透性。',
                time: '30分钟前'
            });
        }
        // 土壤水分分布预警
        if (Math.random() > 0.8) {
            alerts.push({
                type: 'moisture',
                level: 'low',
                title: '土壤水分分布不均',
                message: '检测到灌区土壤水分分布不均匀，建议调整喷头覆盖范围和灌溉强度。',
                time: '2小时前'
            });
        }

        return alerts;
    },

    // 生成设备预警
    generateDeviceAlerts() {
        const alerts = [];
        
        // 水泵故障预警
        if (Math.random() > 0.85) {
            alerts.push({
                type: 'device',
                level: 'high',
                title: '水泵运行异常',
                message: '3号水泵压力波动异常（当前：2.8MPa，正常：3.2-3.5MPa），可能存在轴承磨损，请及时检修。',
                time: '15分钟前'
            });
        }
        
        // 管道压力预警
        if (Math.random() > 0.8) {
            alerts.push({
                type: 'device',
                level: 'medium',
                title: '管道压力异常',
                message: '主管道B段压力持续偏高（当前：4.2MPa，正常：3.5-4.0MPa），建议检查是否存在堵塞。',
                time: '45分钟前'
            });
        }
        
        // 设备运行时间预警
        if (Math.random() > 0.9) {
            alerts.push({
                type: 'device',
                level: 'medium',
                title: '设备维护提醒',
                message: '1号水泵已运行1200小时，达到维护周期，请安排例行检修。',
                time: '2小时前'
            });
        }
        
        // 喷头堵塞预警
        if (Math.random() > 0.85) {
            alerts.push({
                type: 'device',
                level: 'low',
                title: '喷头异常',
                message: 'B3区域多个喷头出水不均，疑似存在堵塞，建议清洗或更换过滤网。',
                time: '1小时前'
            });
        }
        
        // 电机温度预警
        if (Math.random() > 0.95) {
            alerts.push({
                type: 'device',
                level: 'high',
                title: '电机温度过高',
                message: '2号水泵电机温度达到85℃，超出安全范围，系统已自动停机，请检查冷却系统。',
                time: '5分钟前'
            });
        }

        return alerts;
    },

    // 生成水质预警
    generateQualityAlerts() {
        const alerts = [];
        
        // pH值异常预警
        if (Math.random() > 0.8) {
            const pH = (7.5 + Math.random()).toFixed(1);
            alerts.push({
                type: 'quality',
                level: 'medium',
                title: '水质pH值异常',
                message: `灌溉水pH值为${pH}，偏高于适宜范围（6.5-7.5），建议添加调节剂或更换水源。`,
                time: '45分钟前'
            });
        }
        
        // 悬浮物含量预警
        if (Math.random() > 0.85) {
            const turbidity = Math.floor(50 + Math.random() * 30);
            alerts.push({
                type: 'quality',
                level: 'low',
                title: '水质浑浊度升高',
                message: `检测到水中悬浮物含量${turbidity}mg/L，超出标准值，建议开启沉淀池过滤系统。`,
                time: '2小时前'
            });
        }
        
        // 盐分含量预警
        if (Math.random() > 0.9) {
            const salinity = (0.8 + Math.random() * 0.4).toFixed(2);
            alerts.push({
                type: 'quality',
                level: 'high',
                title: '水质盐分超标',
                message: `灌溉水盐分含量${salinity}g/L，超出作物耐受范围，存在盐害风险，建议更换水源。`,
                time: '30分钟前'
            });
        }
        
        // 水温异常预警
        if (Math.random() > 0.95) {
            const temp = Math.floor(32 + Math.random() * 5);
            alerts.push({
                type: 'quality',
                level: 'medium',
                title: '水温异常',
                message: `当前灌溉水温${temp}℃，偏高于适宜温度范围，建议在清晨或傍晚进行灌溉。`,
                time: '1小时前'
            });
        }
        
        // 肥料浓度预警
        if (Math.random() > 0.85) {
            const concentration = (200 + Math.random() * 100).toFixed(0);
            alerts.push({
                type: 'quality',
                level: 'medium',
                title: '肥料浓度异常',
                message: `水肥一体化系统检测到肥料浓度${concentration}ppm，超出设定范围，请检查施肥装置。`,
                time: '20分钟前'
            });
        }

        return alerts;
    },

    // 获取预警图标
    getAlertIcon(type) {
        const icons = {
            moisture: '💧',
            device: '⚠️',
            quality: '🌊'
        };
        return icons[type] || '⚠️';
    },

    // 更新预警统计
    updateAlertSummary() {
        const alerts = this.generateAlerts('all');
        const pending = alerts.length;
        const handled = Math.floor(Math.random() * 5);
        const total = pending + handled;

        document.getElementById('todayAlerts').textContent = total;
        document.getElementById('pendingAlerts').textContent = pending;
        document.getElementById('handledAlerts').textContent = handled;
    },

    // 处理预警
    handleAlert(btn) {
        const alertItem = btn.closest('.alert-item');
        alertItem.style.opacity = '0.5';
        btn.disabled = true;
        btn.textContent = '已处理';
        this.updateAlertSummary();
    },

    // 忽略预警
    ignoreAlert(btn) {
        const alertItem = btn.closest('.alert-item');
        alertItem.style.display = 'none';
        this.updateAlertSummary();
    }
}); 